package cn.edu.zjut.security;

import cn.edu.zjut.base.BaseController;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author:ZhouDan
 * @date: 2020/8/10
 * @version: 1.0
 */
@Component
public class MyAuthenticationFailHandler extends BaseController implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        Map<String, Object> userMap = new HashMap<>();
        Map<String, Object> map = response(1004, userMap);
        PrintWriter out = response.getWriter();
        JSONObject json = new JSONObject();
        for (Map.Entry<String, Object> map1 : map.entrySet()) {
            json.put(map1.getKey(), map1.getValue());
        }
        out.write(json.toString());
    }
}
